# -*- coding=utf8 -*-
import django.forms as forms
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate

class RegistrationForm(forms.ModelForm):
    error_messages = {
        "duplicate_username": u"Такое имя уже существует!",
        "duplicate_email": u"Такой email уже существует!",
        "password_mismatch": u"Введите одинаковые пароли!"
        }
    username = forms.RegexField(label=u"Логин", max_length=30,
                                regex=r"[a-zA-Z0-9]{4,30}",
                                help_text = u"",
                                error_messages = {"invalid": u"Нужно ввести не менее 4 знаков. Разрешены ТОЛЬКО буквы или числа"})
    email = forms.EmailField(label=u"E-mail")
    password1 = forms.CharField(label=u"Пароль", widget=forms.PasswordInput)
    password2 = forms.CharField(label=u"Подтверждение пароля", widget=forms.PasswordInput, help_text=u"Подтвердите пароль")

    class Meta:
        model = User
        fields = ("username", "email")

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages["duplicate_username"])

    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(self.error_messages["duplicate_email"])


    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(self.error_messages["password_mismatch"])
        return password2

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

    def login_user(self, request):
        u = authenticate(username=self.cleaned_data["username"], password=self.cleaned_data["password1"])
        if u:
            login(request, u)
